package com.zr.web;

import com.zr.pojo.User;
import com.zr.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    UserService service = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //System.out.println(user);
        // 获取用户输入的验证码
        String checkCode = req.getParameter("checkCode");
        // 程序生成的验证码，从Session获取
        HttpSession session = req.getSession();
        String checkCodeGen = (String)session.getAttribute("checkCodeGen");

        System.out.println(checkCode);
        System.out.println(checkCodeGen);

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){
            req.setAttribute("register_msg","验证码错误");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            // 不允许注册
            return;
        }

        //2.调用Service注册
        boolean flag = service.register(user);
        //3. 判断注册成功与否
        if(flag) {
            //注册功能，跳转登陆页面
            req.setAttribute("register_msg","注册成功，请登录");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);

        }else {
            //注册失败，跳转到注册页面
            req.setAttribute("register_msg","用户名已存在");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
